package com.hyc.sso_server.Listener;

import com.hyc.sso_server.token.userTokenMap;
import com.hyc.sso_server.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.nio.charset.StandardCharsets;

/**
 * @projectName: SSO_self
 * @package: com.hyc.sso_server.Listener
 * @className: keyexpireListener
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/1/11 17:30
 * @version: 1.0
 */
public class keyexpireListener extends KeyExpirationEventMessageListener {

    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(keyexpireListener.class);

    /**
     * @param listenerContainer must not be {@literal null}.
     */
    public keyexpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    //实现信息方法，打印监听日志，后续可能对过期key处理
    /*redis key 过期：pattern=__keyevent@*__:expired,channel=__keyevent@0__:expired,key=name
     * 测试完毕
     * */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        //  如果登录令牌过期,则删除token 要求用户重新登录
        for (String s : userTokenMap.tokenmap.keySet()) {
            if (key.equals(s)) {
                RedisUtils.redisTemplate.opsForSet().remove("token", userTokenMap.tokenmap.get(key));
                System.out.println("删除成功");
            }
        }
        LOGGER.info("redis key 过期：pattern={},channel={},key={}", new String(pattern), channel, key);
    }
}
